package com.cc.cbdb.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cc.cbdb.R;
import com.cc.cbdb.adapter.HomeFragmentPagerAdapter;
import com.cc.cbdb.common.constants.Constant;
import com.cc.cbdb.common.report.ReportHelper;
import com.cc.cbdb.common.utils.NetRequest;
import com.cc.cbdb.common.utils.StringUtil;
import com.cc.cbdb.common.utils.ToastUtil;
import com.cc.cbdb.entity.PageBean;
import com.cc.cbdb.entity.QBiogCustom;
import com.cc.cbdb.entity.ReportData;
import com.cc.cbdb.fragment.AboutFragment;
import com.cc.cbdb.fragment.QueryFragment;
import com.cc.cbdb.fragment.RecommendFragment;
import com.cc.cbdb.view.LoadingDialog;
import com.cc.cbdb.view.x5WebView.X5WebView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import okhttp3.Request;

public class HomeActivity extends FragmentActivity implements View.OnClickListener {

    private static final String TAG = "HomeActivity";
    private ArrayList<Fragment> fragments = new ArrayList<Fragment>();
    private ArrayList<QBiogCustom> mResults = new ArrayList<>();
    private ViewPager viewPager;
    private RelativeLayout bottom_recommend, bottom_query, bottom_about;
    private TextView tv_title;
    private LoadingDialog mLoadingDialog;

    //推荐算法变量
    private int mTotalPage = 0,mcurrentPage = 1;//分页参数

    private int mPersonSize, mNameSize, mOtherSize;//四类推荐依据数据总量

    private int mRdNameTimes, mRdPersonTimes, mRdOhterTimes;//四类推荐次数

    public static boolean isNoPersonRD = false ,isNoRelation  = false, isNoRecommed = false;

    private ReportData reqCondition;//最终的推荐请求参数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
    }


    private void initView() {
        viewPager = findViewById(R.id.viewPager);
        tv_title = findViewById(R.id.titleBar);
        bottom_recommend = findViewById(R.id.bottom_recommend);
        bottom_query = findViewById(R.id.bottom_query);
        bottom_about = findViewById(R.id.bottom_about);

        bottom_recommend.setOnClickListener(this);
        bottom_query.setOnClickListener(this);
        bottom_about.setOnClickListener(this);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position){
                    case 0:
                        tv_title.setText("人物推荐");
                        break;
                    case 1:
                        tv_title.setText("中国历代人物传记资料库");
                        break;
                    case 2:
                        tv_title.setText("关于");
                        break;
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setOffscreenPageLimit(3); //设置向左和向右都缓存limit个页面

        LoadingDialog.Builder builder = new LoadingDialog.Builder(this);
        builder.setMessage("正在推荐中");
        mLoadingDialog = builder.create();
    }

    private void initData() {
        RecommendFragment recommendFm = new RecommendFragment();
        QueryFragment queryFm = new QueryFragment();
        AboutFragment aboutFm = new AboutFragment();

        fragments.add(recommendFm);
        fragments.add(queryFm);
        fragments.add(aboutFm);

        HomeFragmentPagerAdapter fragmentPagerAdapter = new HomeFragmentPagerAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(fragmentPagerAdapter);
        viewPager.setCurrentItem(1);

        //X5内核初始化
        new X5WebView(getApplication());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bottom_recommend:
                viewPager.setCurrentItem(0);
                recommendData();
                break;
            case R.id.bottom_query:
                viewPager.setCurrentItem(1);
                break;
            case R.id.bottom_about:
                viewPager.setCurrentItem(2);
                break;
        }
    }

    /**
     * 推荐算法
     */
    private void recommendData() {
        //引导推荐分支
        if (mcurrentPage < mTotalPage) {
            //推荐数据的下一页
            mcurrentPage++;
            if (reqCondition != null) {
                getDataAsync();
            }else {
                ToastUtil.showShort(this,"没有更多推荐1~");
            }
            if (isNoPersonRD) {
                reqCondition = null;
            }
        }else if (!isNoRecommed){
            buildRDParam();
            if (reqCondition != null) {
                getDataAsync();
            }else {
                ToastUtil.showShort(this,"没有更多推荐2~");
            }
        }else {
            ToastUtil.showShort(this,"没有更多推荐3~");
        }
    }

    /**
     * 构建推荐参数
     */
    private void buildRDParam(){
        ReportHelper reportHelper = ReportHelper.getInstance(this);
        //1、先获取用户感兴趣的人物
        List<ReportData> interestedPerson = new ArrayList<>();

        Comparator<ReportData> comparator = new Comparator<ReportData>() {

            @Override
            public int compare(ReportData reportData, ReportData t1) {
                if (reportData.getTimes() > t1.getTimes()) {
                    return 1;
                } else if (reportData.getTimes() == t1.getTimes()) {
                    return 0;
                } else {
                    return -1;
                }
            }
        };

        //1.1 从人物详情查询获取
        List<ReportData> personInfoList = reportHelper.getDataDesc(ReportHelper.PERSONINFO, ReportHelper.TABTYPE1);
        if (!StringUtil.isEmpty(personInfoList)) {
            interestedPerson.addAll(personInfoList);
        } else {
            //1.2 如果人物详情查询没有，则从人名查询历史获取
            isNoRelation = true;
        }

        if (!StringUtil.isEmpty(interestedPerson) || !isNoPersonRD) {
            // 2.如有感兴趣的人，且人物还没推荐完，则从最感兴趣的人物开始倒序进行推荐
            Collections.sort(interestedPerson, comparator);

            if (isNoRelation) {
                // 2.1如果只有姓名，则推荐同姓的人物
                List<ReportData> personNameList = reportHelper.getDataDesc(ReportHelper.PERSONNAME, ReportHelper.TABTYPE2);
                if (!StringUtil.isEmpty(personNameList)) {
                    Iterator<ReportData> iterator = personNameList.iterator();
                    while(iterator.hasNext()){
                        ReportData data = iterator.next();
                        if (data.getName().length() < 2){
                            iterator.remove();
                        }
                    }
                    mNameSize = personNameList.size();
                    mRdNameTimes++;
                    if (mRdNameTimes <= mNameSize){
                        ReportData data = personNameList.get(mRdNameTimes-1);
                        String name = data.getName();
                        data.setName(name.length() > 2 ? name.substring(0,2) : name);
                        reqCondition = data;
                        if (mRdNameTimes == mNameSize) {
                            //人物相关都推荐完了
                            isNoPersonRD = true;
                        }
                    }
                }
            } else {
                // 2.2如果有人物id，则根据人物关系推荐
                mPersonSize = interestedPerson.size();

                List<ReportData> kinshipList = reportHelper.getDataDesc(ReportHelper.KINSHIP, ReportHelper.TABTYPE1);
                List<ReportData> assocList = reportHelper.getDataDesc(ReportHelper.ASSOC, ReportHelper.TABTYPE2);
                List<ReportData> relationList = new ArrayList<>();
                if (!StringUtil.isEmpty(kinshipList)) {
                    relationList.addAll(kinshipList);
                }
                if (!StringUtil.isEmpty(assocList)) {
                    relationList.addAll(assocList);
                }

                mRdPersonTimes++;
                if (mRdPersonTimes <= mPersonSize){
                    ReportData personData = interestedPerson.get(mRdPersonTimes-1);

                    if (!StringUtil.isEmpty(relationList)){
                        // 如果用户有感兴趣的人物关系则推荐最感兴趣人物关系前后40位的相关人物
                        Collections.sort(relationList, comparator);
                        ReportData relationData = relationList.get(0);
                        // 取出频率最多的，推荐前后24个关系
                        int relationId = Integer.parseInt(relationData.getId());
                        StringBuilder sb = new StringBuilder(relationId+"");
                        for (int i = 1; i <= 40; i++) {
                            sb.append(",");
                            sb.append(relationId - i);
                            sb.append(",");
                            sb.append(relationId + i);
                        }
                        personData.setName(sb.toString());
                        personData.setTabName(relationData.getTabName());
                    }else {
                        // 如果用户没有感兴趣的人物关系则随机推荐亲属关系或者社会关系
                        Random random = new Random();
                        int flag = random.nextInt(2) + 1;
                        personData.setTabName(flag == 1 ? ReportHelper.KINSHIP : ReportHelper.ASSOC);
                    }
                    reqCondition = personData;
                    if (mRdPersonTimes == mPersonSize){
                        //关系人物都推荐完了
                        isNoRelation = true;
                    }
                }
            }
        } else {
            // 3.如果没有人物和相关联系人，则根据查询过的条件进行推荐
            List<ReportData> interestedParams = new ArrayList<>();

            List<ReportData> officeList = reportHelper.getDataDesc(ReportHelper.OFFICE, ReportHelper.TABTYPE2);
            List<ReportData> entrytypeList = reportHelper.getDataDesc(ReportHelper.ENTRYTYPE, ReportHelper.TABTYPE1);
            List<ReportData> addressList = reportHelper.getDataDesc(ReportHelper.ADDRESS, ReportHelper.TABTYPE1);
//            List<ReportData> addrTypeList = reportHelper.getDataDesc(ReportHelper.ADDRTYPE, ReportHelper.TABTYPE1);
            List<ReportData> dyList = reportHelper.getDataDesc(ReportHelper.DY, ReportHelper.TABTYPE1);
            List<ReportData> enthnicityList = reportHelper.getDataDesc(ReportHelper.ENTHNICITY, ReportHelper.TABTYPE1);
            List<ReportData> appointmentList = reportHelper.getDataDesc(ReportHelper.APPOINTMENT, ReportHelper.TABTYPE2);
            List<ReportData> instList = reportHelper.getDataDesc(ReportHelper.INST, ReportHelper.TABTYPE1);
            List<ReportData> bioginstList = reportHelper.getDataDesc(ReportHelper.BIOGINST, ReportHelper.TABTYPE1);
            List<ReportData> statusList = reportHelper.getDataDesc(ReportHelper.STATUS, ReportHelper.TABTYPE1);
            List<ReportData> textList = reportHelper.getDataDesc(ReportHelper.TEXT, ReportHelper.TABTYPE1);

            if (!StringUtil.isEmpty(officeList)) {
                interestedParams.addAll(officeList);
            }
            if (!StringUtil.isEmpty(entrytypeList)) {
                interestedParams.addAll(entrytypeList);
            }
            if (!StringUtil.isEmpty(addressList)) {
                interestedParams.addAll(addressList);
            }
            if (!StringUtil.isEmpty(dyList)) {
                interestedParams.addAll(dyList);
            }
            if (!StringUtil.isEmpty(enthnicityList)) {
                interestedParams.addAll(enthnicityList);
            }
            if (!StringUtil.isEmpty(appointmentList)) {
                interestedParams.addAll(appointmentList);
            }
            if (!StringUtil.isEmpty(instList)) {
                interestedParams.addAll(instList);
            }
            if (!StringUtil.isEmpty(bioginstList)) {
                interestedParams.addAll(bioginstList);
            }
            if (!StringUtil.isEmpty(statusList)) {
                interestedParams.addAll(statusList);
            }
            if (!StringUtil.isEmpty(textList)) {
                interestedParams.addAll(textList);
            }

            Collections.sort(interestedParams, comparator);

            if (!StringUtil.isEmpty(interestedParams)) {
                mOtherSize = interestedParams.size();
                if (mRdOhterTimes < mOtherSize) {
                    reqCondition = interestedParams.get(mRdOhterTimes);
                    mRdOhterTimes++;
                }
            }else {
                //没有更多推荐
                isNoRecommed = true;
            }
        }
    }

    /**
     * 异步请求后台数据
     */
    private void getDataAsync() {
        mLoadingDialog.show();
        String url = Constant.DOMAIN_PROJECT;
        String id = reqCondition.getId() == null ? "" : reqCondition.getId();
        String name = reqCondition.getName() == null ? "" : reqCondition.getName();
        final HashMap<String, String> reqParams = new HashMap<>();
        reqParams.put("pageNum", mcurrentPage + "");
        switch (reqCondition.getTabName()) {
            case ReportHelper.PERSONNAME:
                url += Constant.URL.URL_QNAME;
                reqParams.put("name", name);
                break;

            case ReportHelper.PERSONINFO:
                url += Constant.URL.URL_QNAME;
                reqParams.put("id", id);
                reqParams.put("name", name);
                break;

            case ReportHelper.ADDRESS:
                url += Constant.URL.URL_QBIOGADDR;
                reqParams.put("cAddrId", id);
                break;

            case ReportHelper.OFFICE:
            case ReportHelper.ENTRYTYPE:
                url += Constant.URL.URL_QBIOGOFF;
                reqParams.put("id", id);
                reqParams.put("tempId", reqCondition.getName() == null ? "" : reqCondition.getName());
                break;

            case ReportHelper.DY:
                url += Constant.URL.URL_QNAME;
                reqParams.put("dy", id);
                break;

            case ReportHelper.CHORONYM:
                url += Constant.URL.URL_QNAME;
                reqParams.put("choronymCode", id);
                break;

            case ReportHelper.ENTHNICITY:
                url += Constant.URL.URL_QNAME;
                reqParams.put("ethnicityCode", id);
                break;

            case ReportHelper.INST:
                url += Constant.URL.URL_QADVANCEDQUERY;
                reqParams.put("instIds", id);
                break;

            case ReportHelper.BIOGINST:
                url += Constant.URL.URL_QADVANCEDQUERY;
                reqParams.put("biogInstIds", id);
                break;

            case ReportHelper.STATUS:
                url += Constant.URL.URL_QADVANCEDQUERY;
                reqParams.put("statusIds", id);
                break;

            case ReportHelper.KINSHIP:
                url += Constant.URL.URL_QKUNSHIPPERSON;
                reqParams.put("personid", id);
                reqParams.put("relationIds", reqCondition.getName() == null ? "" : reqCondition.getName());
                break;

            case ReportHelper.ASSOC:
                url += Constant.URL.URL_QASSOCPERSON;
                reqParams.put("personid", id);
                reqParams.put("relationIds", reqCondition.getName() == null ? "" : reqCondition.getName());
                break;
        }

        Log.d(TAG, "requestParams: " + reqParams);

        NetRequest.getFormRequest(url, reqParams, new NetRequest.DataCallBack() {
            @Override
            public void requestSuccess(String result) throws Exception {
                Log.d(TAG, "json返回数据：" + result);

                PageBean<QBiogCustom> pageBean = new Gson().fromJson(result, new TypeToken<PageBean<QBiogCustom>>() {
                }.getType());
                mResults.clear();
                mResults.addAll(pageBean.getRecordList());
                mTotalPage = pageBean.getTotalPage();
                if (StringUtil.isEmpty(mResults)) {
                    //如果没有结果，继续使用下一条件进行推荐
                    recommendData();
                } else {
                    mLoadingDialog.dismiss();
                    //如果有推荐，则通知推荐fragment进行数据更新
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("recommendData", mResults);
                    RecommendFragment fragment = (RecommendFragment) fragments.get(0);
                    fragment.setArguments(bundle);
                    fragment.updataFragment();
                }
            }

            @Override
            public void requestFailure(Request request, IOException e) {
                ToastUtil.showShort(HomeActivity.this, "请求错误！");
            }
        });
    }


}
